/* Copyright 2009 Palm, Inc.  All rights reserved. */

var PrefSetter = {

    identifier: 'palm://com.palm.telephony',

    isValidPin: function(pin){
        var ret = (pin !== undefined &&
        pin.length !== undefined &&
        pin.length >= 4 &&
        pin.length <= 8 );
        return ret;
    },

	deviceLockUnlock: function(pin, type, block, callback){
		TelephonyService.deviceLockUnlock(pin, type, block, this.deviceLockUnlockCallback.bind(this,callback));
	},

	deviceLockUnlockCallback: function(callback, payload){
		if(payload && payload.returnValue == true){//success
            callback(true);
	     }
     	else {//failure
            callback(false, $L("Please try again"));
	    }
	},
	
    unlockTelephony: function(pin, callback){
        Mojo.log("unlockTelephony: Valid PIN")
		TelephonyService.unlockTelephony(pin[0], this.unlockTelephonyCallback.bind(this, callback));
	},

	unlockTelephonyCallback: function(callback, payload)
	{
		Mojo.Log.info("unlockTelephonyCallback payload:"+Object.toJSON(payload))
		if(payload && payload.returnValue == true){//success
            callback(true);
	     }
     	else if(payload && payload.returnValue == false){//failure
        	//SIM is now PUK locked
			if (payload.errorCode == 3) {
				callback(false, "no dial");
				var pincodeArgs = {
					title: [$L("SIM card locked"), $L("Enter new PIN"), $L("Confirm new PIN")],
					pinPages: 3,
					msg: [$L("Enter PUK to reset PIN"), $L("Enter 4-8 numbers for new PIN"),$L("Enter 4-8 numbers for new PIN")],
					callbackHandler: (function(callback, pin){
						PrefSetter.resetPin1(pin, callback)
					}).bind(this)
				}

				Mojo.Controller.stageController.delegateToSceneAssistant('handlePUKParams', pincodeArgs);
			}
	        else{ 
				if (Messages.unlockTelephonyError[payload.errorCode] !== undefined) {
					payload.errorText = Messages.unlockTelephonyError[payload.errorCode].toString();
				} else {
					payload.errorText = Messages.unlockTelephonyError[Messages.defaultErrorIndex].toString();
				}

	            if (payload.extended && payload.extended.attemptsRemaining) {
					var str = Mojo.Format.formatChoice(payload.extended.attemptsRemaining, 
					$L("1#one try remaining|##{num} tries remaining"), 
					{num: PrefSetter.numberToWord(payload.extended.attemptsRemaining)});
					callback(false, str);
	            }
	            else {
	                callback(false, payload.errorText);
	            }
    	}
    	}
    },
    
    
    //relaunch the phoneprefs app to display the puk lock dialog
    displayPuk1Lock: function(){
		SystemService.relaunchPhoneprefsService("puk1Lock");    
    },
    
    //relaunch the phoneprefs app to display the puk lock dialog
    displayPuk2Lock: function(){
		SystemService.relaunchPhoneprefsService("puk2Lock");    
    },
    
    resetPin1: function(pin, callback){
        if (!PrefSetter.isValidPin(pin[1]) || !PrefSetter.isValidPin(pin[2])) {
            callback(false, $L("Invalid PIN"))
            return;
        }
		TelephonyService.pin1Reset(pin[0], pin[1], pin[2], this.pin1ResetCallback.bind(this, callback));        
    },
	
	pin1ResetCallback: function(callback, payload){
		if(payload && payload.returnValue == true){//success
			Mojo.log("PIN reset succeeded");
            callback(true);
			Mojo.Controller.appController.showBanner(
				{
					icon: "images/notification-small-handset.png",
					messageText: $L("PIN Changed"),
					soundClass: 'none'
				}, 
			{},'');
            //Mojo.Controller.appController.mainController.window.close();
        }
        else if(payload && payload.returnValue == false) {//failure
        	if(payload.errorCode == 4){
				callback(false, 'simlocked')
			}
			else if (Messages.pukUnlockError[payload.errorCode] !== undefined) {
				payload.errorText = Messages.pukUnlockError[payload.errorCode].toString();
			} else {
				payload.errorText = Messages.pukUnlockError[Messages.defaultErrorIndex].toString();
			}
            if (payload.extended && payload.extended.attemptsRemaining) {//todo: convert errorText to local error string
				var str = Mojo.Format.formatChoice(payload.extended.attemptsRemaining, 
				$L("1#one try remaining|##{num} tries remaining"), 
				{num: PrefSetter.numberToWord(payload.extended.attemptsRemaining)});
				callback(false, str, $L("PUK Incorrect"));
            }
            else {
                callback(false, payload.errorText, $L("PUK Incorrect"));
            }
        }
    },
    
    resetPin2: function(pin, callback){
		if (!PrefSetter.isValidPin(pin[1]) || !PrefSetter.isValidPin(pin[2])) {
            callback(false, $L("Invalid PIN2"))
            return;
        }
		TelephonyService.pin2Reset(pin[0], pin[1], pin[2], this.pin2ResetCallback.bind(this, callback));        
    },

	pin2ResetCallback: function(callback, payload){
		if(payload && payload.returnValue == true){//success
			Mojo.log("PIN2 reset succeeded");
            callback(true);
			Mojo.Controller.appController.showBanner(
				{
					icon: "images/notification-small-handset.png",
					messageText: $L("PIN2 Changed"),
					soundClass: 'none'
				}, 
			{},'');
//			this.controller.stageController.popScene();
            //Mojo.Controller.appController.mainController.window.close();
        }
        else if(payload && payload.returnValue == false) {//failure
 		   	if(payload.errorCode == 4){
				callback(false, 'simlocked')
			}
			else if (Messages.pukUnlockError[payload.errorCode] !== undefined) {
				payload.errorText = Messages.pukUnlockError[payload.errorCode].toString();
			} else {
				payload.errorText = Messages.pukUnlockError[Messages.defaultErrorIndex].toString();
			}
           if (payload.extended && payload.extended.attemptsRemaining) {
				var str = Mojo.Format.formatChoice(payload.extended.attemptsRemaining, 
				$L("1#one try remaining|##{num} tries remaining"), 
				{num: PrefSetter.numberToWord(payload.extended.attemptsRemaining)});
				callback(false, str, $L("PUK Incorrect"));
            }
            else {
                callback(false, payload.errorText);
            }
        }
    },
    
 
	setFDNCallback: function(status, callback, payload){
		if(payload && payload.returnValue == true){//success
			Settings.fdnOn = status;
			callback(true);
		}
		else if(payload && payload.returnValue == false){//failure
	        if (payload.errorCode == 3) {
	            callback(false, "no dial");
//				this.controller.stageController.popScene("setFDNCallback");
//    	        PrefSetter.displayPuk2Lock();
				var pincodeArgs = {
					title: [$L("Fixed dialing enabled"), $L("Enter new PIN2"), $L("Confirm new PIN2")],
					pinPages: 3,
					msg: [$L("Enter PUK2 to reset PIN2"), $L("Enter 4-8 numbers for new PIN2"),$L("Enter 4-8 numbers for new PIN2")],
					callbackHandler: (function(callback, pin){
						PrefSetter.resetPin2(pin, callback)
					}).bind(this)
				}
				Mojo.Controller.stageController.delegateToSceneAssistant('handlePUKParams', pincodeArgs, 2);
        	}
	        else {
	 			if (Messages.fdnEnableError[payload.errorCode] !== undefined) {
					payload.errorText = Messages.fdnEnableError[payload.errorCode].toString();
				} else {
					payload.errorText = Messages.fdnEnableError[Messages.defaultErrorIndex].toString();
				}
				if (payload.extended && payload.extended.attemptsRemaining) {
					var str = Mojo.Format.formatChoice(payload.extended.attemptsRemaining, 
					$L("1#one try remaining|##{num} tries remaining"), 
					{num: PrefSetter.numberToWord(payload.extended.attemptsRemaining)});
					callback(false, str);
				}
				else {
					callback(false, payload.errorText);
				}
            }
		}
},
    
    dial: function(number){
        Mojo.log("PrefSetter: dialing " + number)
        var request = new Mojo.Service.Request("palm://com.palm.applicationManager/open", {
            parameters: {
                id: 'com.palm.app.phone',
                params: {
                    "number": number,
					"locale": Mojo.Locale.current
                }
            }
        });
    },

	numberToWord: function(number){
		var word=[$L('Zero'),$L('One'),$L('Two'), $L('Three'),$L('Four'),$L('Five'),$L('Six'),$L('Seven'),$L('Eight'),$L('Nine')];
		return word[number];
	}
};
